<template>
  <el-container>
    <el-aside style="width: 200px">
      <el-col>
        <h4 class="mb-2" style="margin-left: 20px">科室</h4>
        <el-menu
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
        >
          <el-sub-menu :index="index" v-for="(item,index) in hdepartments">
            <template #title>
              <el-icon><CirclePlusFilled /></el-icon>
              <span>{{ item.name }}</span>
            </template>
            <el-menu-item :index="index + '-' + index1" v-for="(item1,index1) in item.clinics"
                          @click="selectClinic(item1)">{{ item1.name }}
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-col>
    </el-aside>
    <el-main>
      <el-card class="box-card" >
        <div v-if="clinic.id == undefined">
          请选择科室
        </div>
        <div v-if="clinic.id != undefined">
          <div class="flex flex-col items-start gap-4" style="display: flex;justify-content: space-between">
            <el-segmented @change="getSchedulingList" v-model="selectDate"
                          :options="dates.map((item)=>{return getDateStr(item)})" size="large"/>
            <el-button type="primary" @click="add()">增加排班</el-button>
          </div>
          <h3>上午</h3>
          <el-table
              :data="morningSchedulings"
              :row-style="{ height: '75px' }"
              style="width: 100%">
            <template #empty>
              暂无排班记录
            </template>
            <el-table-column
                prop="id"
                label="编号"
                width="100px"
            >
            </el-table-column>
            <el-table-column
                prop="title"
                label="标题"
                width="100px">
            </el-table-column>
            <el-table-column
                prop="title"
                label="坐班医生"
                width="200px">
              <template v-slot="scope">
                <div style="width: 100%;display:flex;align-items: center">
                  <img :src="scope.row.doctor.icon != '' && scope.row.doctor.icon != null ? scope.row.doctor.icon : 'https://tse1-mm.cn.bing.net/th/id/OIP-C.OfF_KChm9LNNYU_jFqVoBwAAAA?o=7&cb=thvnextc2rm=3&rs=1&pid=ImgDetMain'"
                       width="60" height="60" style="margin-right: 40px">
                  <span>{{ scope.row.doctor.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                label="开始时间"
                width="120px"
            >
              <template v-slot="scope">
                {{ getDateTimeStr(new Date(scope.row.starttime)) }}
              </template>
            </el-table-column>
            <el-table-column
                label="结束时间"
                width="120px">
              <template v-slot="scope">
                {{ getDateTimeStr(new Date(scope.row.endtime)) }}
              </template>
            </el-table-column>
            <el-table-column
                label="就诊地址"
                width="150">
              <template v-slot="scope">
                {{ clinic.name + scope.row.roomAddress.floor + '层' + scope.row.roomAddress.roomno }}
              </template>
            </el-table-column>
            <el-table-column
                prop="price"
                label="挂号费用"
                width="80px">
            </el-table-column>
            <el-table-column
                prop="count"
                label="总数"
                width="80px">
            </el-table-column>
            <el-table-column
                prop="leaveCount"
                label="剩余数量"
                width="80px">
              <template v-slot="scope">
                <span
                    :class="{red: scope.row.leaveCount == 0,green: scope.row.leaveCount > 0}">{{ scope.row.leaveCount }}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="状态"
                width="150px">
              <template v-slot="scope">
                <span :class="{red: scope.row.state == 0,green: scope.row.state == 1}" style="display: flex"><span
                    style="font-size: 20px">•</span>{{ scope.row.state == 0 ? '已请假' : '正常就诊' }}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="操作">
              <template v-slot="scope">
                <el-button type="info" @click="update(scope.row)">修改信息</el-button>
                <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <h3>下午</h3>
          <el-table
              :data="afternoonSchedulings"
              :row-style="{ height: '75px' }"
              style="width: 100%">
            <template #empty>
              暂无排班记录
            </template>
            <el-table-column
                prop="id"
                label="编号"
                width="100px"
            >
            </el-table-column>
            <el-table-column
                prop="title"
                label="标题"
                width="100px">
            </el-table-column>
            <el-table-column
                prop="title"
                label="坐班医生"
                width="200px">
              <template v-slot="scope">
                <div style="width: 100%;display:flex;align-items: center">
                  <img :src="scope.row.doctor.icon != '' && scope.row.doctor.icon != null ? scope.row.doctor.icon : 'https://tse1-mm.cn.bing.net/th/id/OIP-C.OfF_KChm9LNNYU_jFqVoBwAAAA?o=7&cb=thvnextc2rm=3&rs=1&pid=ImgDetMain'"
                       width="60" height="60" style="margin-right: 40px">
                  <span>{{ scope.row.doctor.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                label="开始时间"
                width="120px"
            >
              <template v-slot="scope">
                {{ getDateTimeStr(new Date(scope.row.starttime)) }}
              </template>
            </el-table-column>
            <el-table-column
                label="结束时间"
                width="120px">
              <template v-slot="scope">
                {{ getDateTimeStr(new Date(scope.row.endtime)) }}
              </template>
            </el-table-column>
            <el-table-column
                label="就诊地址"
                width="150">
              <template v-slot="scope">
                {{ clinic.name + scope.row.roomAddress.floor + '层' + scope.row.roomAddress.roomno }}
              </template>
            </el-table-column>
            <el-table-column
                prop="price"
                label="挂号费用"
                width="80px">
            </el-table-column>
            <el-table-column
                prop="count"
                label="总数"
                width="80px">
            </el-table-column>
            <el-table-column
                prop="leaveCount"
                label="剩余数量"
                width="80px">
              <template v-slot="scope">
                <span
                    :class="{red: scope.row.leaveCount == 0,green: scope.row.leaveCount > 0}">{{ scope.row.leaveCount }}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="状态"
                width="150px">
              <template v-slot="scope">
                <span :class="{red: scope.row.state == 0,green: scope.row.state == 1}" style="display: flex"><span
                    style="font-size: 20px">•</span>{{ scope.row.state == 0 ? '已请假' : '正常就诊' }}</span>
              </template>
            </el-table-column>
            <el-table-column
                label="操作">
              <template v-slot="scope">
                <el-button type="info" @click="update(scope.row)">修改信息</el-button>
                <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-main>
  </el-container>
  <el-dialog :title="form.id == null ? '增加排班' : '修改排班'" v-model="formVisible" @close="clear">
    <el-form :model="form">
      <el-form-item label="标题" :label-width="formLabelWidth">
        <el-input v-model="form.title" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="坐班医生" :label-width="formLabelWidth">
        <el-select v-model="form.did" placeholder="请选择医生">
          <el-option v-for="item in doctors" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间和结束时间"  :label-width="formLabelWidth">
        <el-select @change="changeTime" v-model="shangwuxiawu"  placeholder="请选择">
          <el-option label="上午" :value="0"></el-option>
          <el-option label="下午" :value="1"></el-option>
        </el-select>
        <el-date-picker
              v-model="startTimeAndEndTime"
              type="datetimerange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              readonly
          />
      </el-form-item>
      <el-form-item label="价格" :label-width="formLabelWidth">
        <el-input v-model="form.price" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="数量" :label-width="formLabelWidth">
        <el-input v-model="form.count" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="排班具体门号" :label-width="formLabelWidth">
          <el-select v-model="form.roomId" placeholder="请选择具体门号">
            <el-option v-for="item in rooms" :label="item.floor + '层' + item.roomno" :value="item.id"></el-option>
          </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="formVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="delDialogVisible" title="提示" width="500" center>
    <span style="font-size: 15px">
      你确定要删除该排班信息吗
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="delDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDel()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//elementplus
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting, Plus,
} from '@element-plus/icons-vue'
import {computed, onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {getDateStr, getDateTimeStr, isSameDay} from '@/util/DateUtil';

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
//=================
const hdepartments = ref([])
onMounted(() => {
  initHdepartments()
  initDates()
})
const user = JSON.parse(sessionStorage.getItem("user"))
const initHdepartments = () => {
  axios.get('/h_department/selectByHid', {params: {hid: user.hid}}).then(res => {
    if (res.data.code == 200) {
      hdepartments.value = res.data.data
    } else {
      ElMessage.error("查找科室失败")
    }
  })
}
//选择诊室右侧
const clinic = ref({})
const selectClinic = (item) => {
  clinic.value = item
  getSchedulingList()
}
//选择日期
const value = ref('Mon')
//初始化从今天开始往后七天的日期
const initDates = () => {
  let dateArray = []
  const today = new Date();
  for (let i = 0; i < 8; i++) {
    // 创建新日期对象（避免引用同一个对象）
    const date = new Date(today.getTime());
    // 设置日期为 today + i 天
    date.setDate(today.getDate() + i);
    dateArray.push(date);
  }
  dates.value = dateArray
}
const dates = ref([])
const selectDate = ref(getDateStr(new Date()))
const getSchedulingList = () => {
  let dateStr = new Date().getFullYear() + "-" + selectDate.value
  axios.get("/scheduling/getSchedulingList", {params: {cid: clinic.value.id, date: dateStr}}).then(res => {
    if (res.data.code == 200) {
      schedulings.value = res.data.data
    } else {
      ElMessage.error("获取排班信息失败")
    }
  })
}
//排班列表展示
const schedulings = ref([])
// 筛选上午的调度项 (小时 < 12)
const morningSchedulings = computed(() => {
  return schedulings.value.filter(s => new Date(s.starttime).getHours() < 12);
})

// 筛选下午的调度项 (小时 >= 12)
const afternoonSchedulings = computed(() => {
  return schedulings.value.filter(s => new Date(s.starttime).getHours() >= 12);
})
//弹窗
const formLabelWidth = '200px'
const form = ref({})
const startTimeAndEndTime = ref([])
const formVisible = ref(false)
const clear = () => {
  form.value = {}
  startTimeAndEndTime.value = []
  formVisible.value = false
  delDialogVisible.value = false
  getSchedulingList()
  shangwuxiawu.value = ''
}
const shangwuxiawu = ref()
const changeTime = (val)=>{
  let year = form.value.date.getFullYear()
  let month = form.value.date.getMonth()
  let day = form.value.date.getDate()
  if (val == 0){
    startTimeAndEndTime.value[0] = new Date(year,month,day,8,0,0)
    startTimeAndEndTime.value[1] = new Date(year,month,day,12,0,0)
  }else {
    startTimeAndEndTime.value[0] = new Date(year,month,day,14,0,0)
    startTimeAndEndTime.value[1] = new Date(year,month,day,18,0,0)
  }
  form.value.starttime = startTimeAndEndTime.value[0]
  form.value.endtime = startTimeAndEndTime.value[1]
}
const save = () => {
  if (form.value.title == null || form.value.did == null || form.value.starttime == null || form.value.endtime == null
  ||form.value.price == null || form.value.count == null || form.value.roomId == null){
    ElMessage.error('请输入完整的信息')
  }else {
      axios.post('scheduling/save',form.value).then(res=>{
        if (res.data.code == 200){
          ElMessage.success('保存成功')
          clear()
        }else {
          ElMessage.error(res.data.msg)
        }
      })
  }
}
const showDialog = () => {
  initdoctors()
  initrooms()
  formVisible.value = true
}
const update = (val)=>{
  showDialog()
  form.value = val
  form.value.cid = clinic.value.id
  form.value.date = new Date(val.date)
  form.value.starttime = new Date(val.starttime)
  form.value.endtime = new Date(val.endtime)
  shangwuxiawu.value = val.starttime.getHours() < 12 ? 0 : 1
  startTimeAndEndTime.value = [form.value.starttime,form.value.endtime]
}
const add = ()=>{
  let dateStr = new Date().getFullYear() + "-" + selectDate.value
  form.value.date = new Date(dateStr)
  form.value.cid = clinic.value.id
  showDialog()
}
//弹窗内容初始化
const doctors = ref({})
const initdoctors = ()=>{
  axios.get('doctor/selByClinicId',{params:{cid:clinic.value.id}}).then(res=>{
    if (res.data.code == 200){
      doctors.value = res.data.data
    }else {
      ElMessage.error("初始化医生列表失败")
    }
  })
}
const rooms = ref({})
const initrooms = ()=>{
  axios.get('room_address/selByClinicId',{params:{cid:clinic.value.id}}).then(res=>{
    if (res.data.code == 200){
      rooms.value = res.data.data
    }else {
      ElMessage.error("初始化医生列表失败")
    }
  })
}
//删除
const delDialogVisible = ref(false)
const delId = ref(0)
const del = (id) => {
  delId.value = id
  delDialogVisible.value = true
}
const confirmDel = () => {
  axios.get('scheduling/delete', {params: {id: delId.value}}).then(res => {
    if (res.data.code == 200) {
      ElMessage.success('删除成功')
      clear()
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
//=======================
</script>

<style scoped>
/*
elementplus
 */
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.red {
  color: #f56c6c;
}

.green {
  color: #67c23a;
}
</style>